package com.example.demo.common.utils;





import com.example.demo.common.vo.Tree;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BuildTree {

	public static Tree build(List<Tree> nodes) {

		if (nodes == null) {
			return null;
		}
		List<Tree> topNodes = new ArrayList<Tree>();

		for (Tree children : nodes) {

			String pid = children.getParentId();
			if (pid == null || "0".equals(pid)) {
				topNodes.add(children);

				continue;
			}

			for (Tree parent : nodes) {
				String id = parent.getId();
				if (id != null && id.equals(pid)) {
					parent.getChildren().add(children);
					children.setHasParent(true);
					parent.setChildren(true);
					continue;
				}
			}

		}

		Tree root = new Tree();
		if (topNodes.size() == 1) {
			root = topNodes.get(0);
		} else {
			root.setId("-1");
			root.setParentId("");
			root.setHasParent(false);
			root.setChildren(true);
			root.setChecked(true);
			root.setChildren(topNodes);
			root.setText("顶级节点");
			Map<String, Object> state = new HashMap<>(16);
			state.put("opened", true);
			root.setState(state);
		}

		return root;
	}

	public static  List<Tree> buildList(List<Tree> nodes, String idParam) {
		if (nodes == null) {
			return null;
		}
		List<Tree> topNodes = new ArrayList<Tree>();

		for (Tree children : nodes) {

			String pid = children.getParentId();
			if (pid == null || idParam.equals(pid)) {
				topNodes.add(children);

				continue;
			}

			for (Tree parent : nodes) {
				String id = parent.getId();
				if (id != null && id.equals(pid)) {
					parent.getChildren().add(children);
					children.setHasParent(true);
					parent.setChildren(true);

					continue;
				}
			}

		}
		return topNodes;
	}

    public static Tree buildTree(List<Tree> treeList){
        //第一层节点
        List<Tree> topTreeList = new ArrayList<>();
        for (Tree child : treeList) {
            if(child.getParentId()==null||"0".equals(child.getParentId())){
                topTreeList.add(child);
                continue;
            }
            // 如果当前节点不是 第一级节点  那么找到该节点的 父节点
            for(Tree parent : treeList){
                if(child.getParentId().equals(parent.getId())){
                    //找到父节点
                    parent.getChildren().add(child);
                    child.setHasParent(true);
                    parent.setChildren(true);
                    continue;
                }
            }
        }
        Tree rootTree = new Tree();
        rootTree.setId("-1");
        rootTree.setText("根节点");
        rootTree.setChildren(topTreeList);
        Map<String,Object> state = new HashMap<>();
        state.put("opened",true);
        rootTree.setState(state);
        return rootTree;
    }
}